package cn.zyjw.service.impl;

import cn.zyjw.domain.SysUserRole;
import cn.zyjw.mapper.SysUserRoleMapper;
import cn.zyjw.service.SysUserRoleService;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zyjw.mapper.SysUserMapper;
import cn.zyjw.domain.SysUser;
import cn.zyjw.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 添加员工
     *
     * @param sysUser
     * @return
     */
    @Override
    @Transactional
    public boolean saveUser(SysUser sysUser) {
        String password = sysUser.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        sysUser.setPassword(encode);
        boolean save = this.save(sysUser);

        String roleStrings = sysUser.getRole_strings();
        if (save && StringUtils.isNotBlank(roleStrings)) {
            String[] roleArr = roleStrings.split(",");
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            for (String s : roleArr) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(sysUser.getId());
                userRole.setRoleId(Long.valueOf(s));
                sysUserRoles.add(userRole);
            }
            sysUserRoleService.saveBatch(sysUserRoles);
        }
        return save;
    }

    /**
     * 员工列表分页查询
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    @Override
    public Page<SysUser> pageList(Page<SysUser> page, QueryWrapper<SysUser> queryWrapper) {
        Page<SysUser> userPage = this.page(page, queryWrapper);
        List<SysUser> records = userPage.getRecords();

        if (page.getTotal() <= 0){
            return userPage;
        }

        Set<Long> userIds = records.stream().map(SysUser::getId).collect(Collectors.toSet());
        List<SysUserRole> sysUserRoles = sysUserRoleService.getBaseMapper().selectList(
                new LambdaQueryWrapper<SysUserRole>()
                        .in(SysUserRole::getUserId, userIds)
        );

        Map<Long, String> map = new HashMap<>();
        sysUserRoles.parallelStream()
                .collect(Collectors.groupingBy(SysUserRole::getUserId))
                .forEach((userId, list) -> {
                    String roleStr = list.parallelStream().map(one -> one.getRoleId().toString()).collect(Collectors.joining(","));
                    map.put(userId, roleStr);
                });

        for (SysUser record : records) {
            record.setRole_strings(map.getOrDefault(record.getId(), null));
        }
        return userPage;
    }

    /**
     * 编辑员工
     *
     * @param sysUser
     * @return
     */
    @Override
    @Transactional
    public boolean updUser(SysUser sysUser) {
        if (StringUtils.isNotBlank(sysUser.getPassword())) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        }
        //调整role权限
        String roleStrings = sysUser.getRole_strings();
        if (StringUtils.isNotBlank(roleStrings)) {
            String[] split = roleStrings.split(",");
            if (split.length > 0) {
                sysUserRoleService.remove(
                        new LambdaQueryWrapper<SysUserRole>()
                                .eq(SysUserRole::getUserId, sysUser.getId())
                );
                ArrayList<SysUserRole> sysUserRoles = new ArrayList<>();
                for (String s : split) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(Long.valueOf(s));
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRoles.add(sysUserRole);
                }
                sysUserRoleService.saveBatch(sysUserRoles);
            }
        }
        return this.updateById(sysUser);
    }

    /**
     * 批量删除员工
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public boolean delUserList(Long[] ids) {
        boolean b = this.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(
                new LambdaQueryWrapper<SysUserRole>()
                        .in(SysUserRole::getUserId, Arrays.asList(ids))
        );
        return b;
    }
}
